package com.duowan.realtime.scheduled.batch.processor;

import com.duowan.common.util.DateConvertUtils;
import com.duowan.realtime.model.RedisKey;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author tangsicheng
 * @version 1.0
 * @since 1.0
 * cover map[kpicode='activUser',dimension=[product="kk",iver="1.10"],kpiValue=1.0]
 * to  map[redisKey = tablePrefix|activUser|iver/1.10/product/kk, redisValue = 1.0l ]
 */
public class MapToRedisKVProcessor implements ItemProcessor<List<Map>, List<Map>> {
    private static final Logger logger = LoggerFactory.getLogger(MapToRedisKVProcessor.class);


    private String tablePrefixFormat;

    @Override
    public List<Map> process(List<Map> item) throws Exception {
        List<Map> result = Lists.transform(item, new Function<Map, Map>() {
            @Override
            public Map apply(Map input) {
                String kpiCode = (String) input.get("kpiCode");
                String kpiValue = (String) input.get("kpiValue");
                Map dimension = (Map) input.get("dimension");
                String redisKey;
                try {
                    redisKey = RedisKey.serRedisKey(getTablePrefix(), kpiCode, dimension);
                } catch (IllegalArgumentException e) {
                    logger.error("转换redis错误", e);
                    return null;
                }
                HashMap tempMap = Maps.newHashMap();
                tempMap.put("redisKey", redisKey);
                tempMap.put("redisValue", kpiValue);
                return tempMap;
            }
        });
        return result;
    }

    private String getTablePrefix() {
        return DateConvertUtils.format(new Date(), tablePrefixFormat);
    }

    public void setTablePrefixFormat(String tablePrefixFormat) {
        this.tablePrefixFormat = tablePrefixFormat;
    }
}
